//
//  PurchaseManager.m
//  ChatForHot
//
//  Created by wr on 2018/10/18.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "PurchaseManager.h"
#import <StoreKit/StoreKit.h>
#import <UMCAnalytics/UMAnalytics/MobClick.h>

@interface PurchaseManager()<SKPaymentTransactionObserver,SKProductsRequestDelegate> {
    NSString           *_purchID;
    HOTCHATCompletionHandle _handle;
    PersonalVipInfoModel *_vipModel;
}

@property (nonatomic, assign) VIPDayType vipDayType;
@end

@implementation PurchaseManager

+ (instancetype)shareInstance {
    static PurchaseManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PurchaseManager alloc] init];
    });
    return manager;
}

- (instancetype)init {
    if (self = [super init]) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    return self;
}

- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)startPurchWithID:(NSString *)purchID model:(PersonalVipInfoModel *)model completeHandle:(HOTCHATCompletionHandle)handle {
    if (purchID) {
        if ([SKPaymentQueue canMakePayments]) {
            // 开始购买服务
            _purchID = purchID;
            _handle = handle;
            _vipModel = model;
            [self HOTCHATCorfimVipDayType];
            [self HOTCHATUMVIPclickAction];
            NSSet *nsset = [NSSet setWithArray:@[purchID]];
            SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
            request.delegate = self;
            [request start];
        }else{
            [self handleActionWithType:HOTCHATPurchNotArrow data:nil];
        }
    }
}

- (void)handleActionWithType:(HOTCHATPurchType)type data:(NSData *)data {
    switch (type) {
        case HOTCHATPurchSuccess:
            NSLog(@"购买成功");
            break;
        case HOTCHATPurchFailed:
            NSLog(@"购买失败");
            break;
        case HOTCHATPurchCancle:
            NSLog(@"用户取消购买");
            break;
        case HOTCHATPurchVerFailed:
            NSLog(@"订单校验失败");
            break;
        case HOTCHATPurchVerSuccess:
            NSLog(@"订单校验成功");
            break;
        case HOTCHATPurchNotArrow:
            NSLog(@"不允许程序内付费");
            break;
        default:
            break;
    }
    if(_handle){
        _handle(type,data);
    }
}

// 交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    @weakify(self)
    NSString * productIdentifier = transaction.payment.productIdentifier;
    NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
    NSString *receipt = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    if (!receipt) {
        [self handleActionWithType:HOTCHATPurchVerFailed data:nil];
        return;
    }
    
    [self handleActionWithType:HOTCHATPurchSuccess data:nil];
    
    if ([productIdentifier length] > 0) {
        // 向自己的服务器验证购买凭证
        NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
        [parameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
        [parameters setValue:@"1003" forKey:@"code"];
        [parameters setValue:@"1" forKey:@"payType"];
        [parameters setValue:@"1" forKey:@"clientType"];
        [parameters setValue:self ->_vipModel.price forKey:@"payMoney"];
        [parameters setValue:[APPINFO defaultManager].appid forKey:@"appid"];
        [parameters setValue:[APPINFO defaultManager].ver forKey:@"appVer"];
        [parameters setValue:@"1" forKey:@"type"];
        [parameters setValue:self ->_purchID forKey:@"productId"];
        //获取应该有的天数
        NSInteger days;
        NSString *durationStr = self ->_vipModel.duration;
        NSString *unitStr = self ->_vipModel.unit;
        if ([unitStr isEqualToString:@"days"]) {
            days = [durationStr integerValue];
        }else {
            days = ([durationStr integerValue]) * 31;
        }
        [parameters setValue:[NSString stringWithFormat:@"%zi",days] forKey:@"days"];
        [NetWorkTool HOTCHATRequestWithStringURL:GETORDERNO_URL progress:^(NSProgress * _Nonnull progress) {
        } RequestWay:@"POST" Parma:parameters SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
            @strongify(self)
            if (isSucess) {
                NSString *orderNo = [resultDictionary valueForKey:@"data"];
                [self verifyPurchaseWith:receipt orderNo:orderNo productId:self ->_purchID];
            }
        } FailureBlock:^(NSError * _Nonnull error) {
        }];
    }
    
}

// 交易失败
- (void)failedTransaction:(SKPaymentTransaction *)transaction{
    if (transaction.error.code != SKErrorPaymentCancelled) {
        [self handleActionWithType:HOTCHATPurchFailed data:nil];
    }else{
        [self handleActionWithType:HOTCHATPurchCancle data:nil];
    }
    
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)verifyPurchaseWith:(id )receipt orderNo:(NSString *)orderNo productId:(NSString *)productId{
    @weakify(self)
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
    [parameters setValue:orderNo forKey:@"orderNo"];
    [parameters setValue:receipt forKey:@"receipt"];
    [parameters setValue:productId forKey:@"productId"];
    
    [NetWorkTool HOTCHATRequestWithStringURL:ORDERAppleVerify_URL progress:^(NSProgress * _Nonnull progress) {
    } RequestWay:@"POST" Parma:parameters SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        @strongify(self)
        if (isSucess) {
            [self handleActionWithType:HOTCHATPurchVerSuccess data:nil];
            [NetWorkTool HOTCHATUpdateToken];
            [self HOTCHATUMVIPBuySucessAction];
        }else {
            [self handleActionWithType:HOTCHATPurchVerFailed data:nil];
        }
    } FailureBlock:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - SKProductsRequestDelegate

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *product = response.products;
    if([product count] <= 0){
        NSLog(@"--------------没有商品------------------");
        [NetWorkTool HOTCHATshowMessage:NSLocalizedString(@"personalVIP3", nil)];
        [self handleActionWithType:HOTCHATPurchFailed data:nil];
        return;
    }
    
    SKProduct *p = nil;
    for(SKProduct *pro in product){
        if([pro.productIdentifier isEqualToString:_purchID]){
            p = pro;
            SKPayment *payment = [SKPayment paymentWithProduct:pro];
             [[SKPaymentQueue defaultQueue] addPayment:payment];
//            break;
        }
    }
    
    NSLog(@"productID:%@", response.invalidProductIdentifiers);
    NSLog(@"产品付费数量:%lu",(unsigned long)[product count]);
    NSLog(@"%@",[p description]);
    NSLog(@"%@",[p localizedTitle]);
    NSLog(@"%@",[p localizedDescription]);
    NSLog(@"%@",[p price]);
    NSLog(@"%@",[p productIdentifier]);
    NSLog(@"发送购买请求");
    
//    SKPayment *payment = [SKPayment paymentWithProduct:p];
   
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"------------------错误-----------------:%@", error);
}

- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"------------反馈信息结束-----------------");
}

#pragma mark - SKPaymentTransactionObserver

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *tran in transactions) {
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:tran];
                 [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                // 消耗型不支持恢复购买
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:tran];
                break;
            default:
                break;
        }
    }
}

- (void)HOTCHATUMtongjiEvent:(NSString *)eventId {
    [MobClick event:eventId];
}

- (void)HOTCHATCorfimVipDayType {
    NSString *durationStr = self ->_vipModel.duration;
    NSString *unitStr = self ->_vipModel.unit;
    if ([unitStr isEqualToString:@"days"]) {
        self.vipDayType = VIPDayType_Days;
    }else {
        if ([durationStr isEqualToString:@"1"]) {
            self.vipDayType = VIPDayType_OneMonth;
        }else if ([durationStr isEqualToString:@"3"]){
            self.vipDayType = VIPDayType_ThreeMonth;
        }else {
            self.vipDayType = VIPDayType_FreeThreeDay;
        }
    }
}

- (void)HOTCHATUMVIPclickAction {
    if (self.vipDayType == VIPDayType_Days) {
        [self HOTCHATUMtongjiEvent:CLICKPURCHASE_VIP_7DAYS_VIPCENTER];
    }else if (self.vipDayType == VIPDayType_OneMonth) {
        [self HOTCHATUMtongjiEvent:CLICKPURCHASE_VIP_1MONTH_VIPCENTER];
    }else if (self.vipDayType == VIPDayType_ThreeMonth) {
        [self HOTCHATUMtongjiEvent:CLICKPURCHASE_VIP_3MONTH_VIPCENTER];
    }else if (self.vipDayType == VIPDayType_FreeThreeDay) {
        [self HOTCHATUMtongjiEvent:CLICKPURCHASEVIEWBUTTON_CHATVIEW];
    }
}

- (void)HOTCHATUMVIPBuySucessAction {
    if (self.vipDayType == VIPDayType_Days) {
        [self HOTCHATUMtongjiEvent:PURCHASESUCCESS_VIP_7DAYS_VIPCENTER];
    }else if (self.vipDayType == VIPDayType_OneMonth) {
        [self HOTCHATUMtongjiEvent:PURCHASESUCCESS_VIP_1MONTH_VIPCENTER];
    }else if (self.vipDayType == VIPDayType_ThreeMonth) {
        [self HOTCHATUMtongjiEvent:PURCHASESUCCESS_VIP_3MONTH_VIPCENTER];
    }else if (self.vipDayType == VIPDayType_FreeThreeDay) {
        [self HOTCHATUMtongjiEvent:SUCCESS_VIP_3FREEDAYS_CHATVIEW];
    }
}
@end
